<template>
    <div>
      <!-- 登录界面 -->
      <div v-if="!isLoggedIn">
        <select v-model="userType">
          <option value="individual">个人</option>
          <option value="group">小组</option>
        </select>
        <select v-model="selectedName" v-if="userType === 'individual'">
          <option v-for="name in names" :key="name" :value="name">{{ name }}</option>
        </select>
        <select multiple v-model="selectedGroupNames" v-if="userType === 'group'">
          <option v-for="name in names" :key="name" :value="name">{{ name }}</option>
        </select>
        <button @click="login">确认</button>
      </div>
      <!-- 答题界面 -->
      <div v-else>
        <div v-if="!question">等待教师发布题目...</div>
        <div v-else>
          <p>{{ question.content }}</p>
          <div v-if="question.type === 'choice'">
            <input type="radio" v-for="option in options" :key="option.id" :value="option.option_text" v-model="answer">
            {{ option.option_text }}
          </div>
          <input type="text" v-if="question.type === 'fill'" v-model="answer">
          <button @click="submitAnswer">提交答案</button>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  import io from 'socket.io-client';
  
  export default {
    data() {
      return {
        userType: 'individual',
        selectedName: '',
        selectedGroupNames: [],
        names: [],
        isLoggedIn: false,
        question: null,
        options: [],
        answer: ''
      };
    },
    mounted() {
      this.socket = io();
      this.socket.on('names', (names) => {
        this.names = names;
      });
      this.socket.on('question', (question, options) => {
        this.question = question;
        this.options = options;
      });
    },
    methods: {
      login() {
        if (this.userType === 'individual') {
          this.socket.emit('login', { type: 'individual', name: this.selectedName });
        } else {
          this.socket.emit('login', { type: 'group', names: this.selectedGroupNames });
        }
        this.isLoggedIn = true;
      },
      submitAnswer() {
        this.socket.emit('submitAnswer', { questionId: this.question.id, answer: this.answer });
      }
    }
  };
  </script>